package com.book.modules.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.common.result.PageInfo;
import com.book.modules.core.entity.DataEntity;
import com.book.modules.core.service.IBaseService;

import java.util.List;

/**
 * Description：
 * @Author： leo.xiong
 * @CreateDate： 2019/10/15 09:30
 * @Email： leo.xiong@suyun360.com
 * Version：1.0
 */
public abstract class BaseServiceImpl<M extends BaseMapper<T>, T extends DataEntity<T>> extends ServiceImpl<M, T> implements IBaseService<T> {
    /**
     * 分页查询数据信息
     * 默认排序规则为新建时间倒叙排序
     *
     * @param entity
     * @param pageInfo
     * @return
     */
    @Override
    public PageInfo<T> findPageList(T entity, PageInfo<T> pageInfo) {
        LambdaQueryWrapper<T> lambdaQuery = Wrappers.lambdaQuery(entity);
        Page<T> page = new Page<>(pageInfo.getPageNo(), pageInfo.getPageSize());
        if (CollectionUtils.isEmpty(page.getOrders())) {
            OrderItem orderItem = new OrderItem();
            orderItem.setColumn("create_date");
            orderItem.setAsc(false);
            page.getOrders().add(orderItem);
        }
        IPage<T> entityPage = super.page(page, lambdaQuery);
        pageInfo.setList(entityPage.getRecords());
        pageInfo.setCount(entityPage.getTotal());
        return pageInfo;
    }

    @Override
    public List<T> findAllList(LambdaQueryWrapper<T> lambdaQuery) {
        return super.list(lambdaQuery);
    }

    @Override
    public List<T> findAllList(T t) {
        LambdaQueryWrapper<T> lambdaQuery = Wrappers.lambdaQuery(t);
        lambdaQuery.orderByDesc(true, T::getCreateDate);
        return findAllList(lambdaQuery);
    }
}
